#####
# This code replicates all tables and figures in 
# Reny, Collingwood, Valenzuela 2018
# Vote Switching in the 2016 Election: How Racial and Immigration Attitudes, Not Economics, Explain Shifts in White Voting
# POQ
#
#####

# Packages #
library(dplyr)
library(MASS)
library(ggplot2)
library(RColorBrewer)
library(stargazer)
library(psych)
library(simcf)
library(stringr)
library(foreign)
library(mice)
library(mitools)
library(separationplot)
library(pROC)
library(plotROC)
library(survey)
library(lmtest)

# Set Directory #

df <- read_csv('clean_cces_16.csv')


# Table 1 -----------------------------------------------------------------

wwc <- df %>% filter(white_anglo==1 & college==0 & voted_2012==1 & voted_2016 == 1)
nwwc <- df %>% filter(white_anglo==1 & college==1 & voted_2012==1 & voted_2016 == 1)

nwwc %>%
  summarise(romney_trump = weighted.mean(vote_romney==1 & vote_trump==1, na.rm=T, w=commonweight)*100,
            obama_clinton = weighted.mean(vote_obama==1 & vote_clinton==1, na.rm=T, w=commonweight)*100,
            third_third = weighted.mean(vote_third_12==1 & vote_third_16==1, na.rm=T, w=commonweight)*100,
            romney_clinton = weighted.mean(vote_romney==1 & vote_clinton==1, na.rm=T, w=commonweight)*100,
            other_clinton = weighted.mean(vote_third_12==1 & vote_clinton==1, na.rm=T, w=commonweight)*100,
            obama_trump = weighted.mean(vote_obama==1 & vote_trump==1, na.rm=T, w=commonweight)*100,
            other_trump = weighted.mean(vote_third_12==1 & vote_trump==1, na.rm=T, w=commonweight)*100) %>%
  t() %>% round(1)
wwc %>%
  summarise(romney_trump = weighted.mean(vote_romney==1 & vote_trump==1, na.rm=T, w=commonweight)*100,
            obama_clinton = weighted.mean(vote_obama==1 & vote_clinton==1, na.rm=T, w=commonweight)*100,
            third_third = weighted.mean(vote_third_12==1 & vote_third_16==1, na.rm=T, w=commonweight)*100,
            romney_clinton = weighted.mean(vote_romney==1 & vote_clinton==1, na.rm=T, w=commonweight)*100,
            other_clinton = weighted.mean(vote_third_12==1 & vote_clinton==1, na.rm=T, w=commonweight)*100,
            obama_trump = weighted.mean(vote_obama==1 & vote_trump==1, na.rm=T, w=commonweight)*100,
            other_trump = weighted.mean(vote_third_12==1 & vote_trump==1, na.rm=T, w=commonweight)*100) %>%
  t() %>% round(1)

# Table 2, Figure 1 and Figure 3 -----------------------------------------------------------------
# Vote Switching Trump ~ all whites

form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college

subD <-  df$white_anglo ==1 & df$pid3factor=='Democrat' &  df$vote_romney == 0 & df$voted_2012 == 1
subI <- df$white_anglo ==1 & df$pid3factor=='Independent' & df$vote_romney == 0 & df$voted_2012 == 1
subR <-  df$white_anglo ==1 & df$pid3factor=='Republican' & df$vote_romney == 0 & df$voted_2012 == 1

# Democrats

summary (trump_shift <-  glm(form, data = df[subD,], family="binomial"))
pe <- coef(trump_shift)
vc <- vcov(trump_shift)
simbetasD <- mvrnorm(1000,pe,vc)

# Independents

summary (trump_shift_i <-  glm(form,data = df[subI,], family="binomial") )
pe <- coef(trump_shift_i)
vc <- vcov(trump_shift_i)
simbetasI <- mvrnorm(1000,pe,vc)

#Republicans

summary (trump_shift_r <-  glm(form,data = df[subR,], family="binomial") )
pe <- coef(trump_shift_r)
vc <- vcov(trump_shift_r)
simbetasR <- mvrnorm(1000,pe,vc)

# model matrices
mmD <- cfMake(form,df[subD,],1)
mmI <- cfMake(form,df[subI,],1)
mmR <- cfMake(form,df[subR,],1)

# anti-black attitudes
mm <- cfChange(mmD,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
antiBlack <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                        lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                        upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                        Party=c('Democrat','Independent','Republican'),
                        Group="All Whites")

# imm attitudes
mm <- cfChange(mmD,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
immDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                     lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                     upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                     Party=c('Democrat','Independent','Republican'),
                     Group="All Whites")

# latgrowth
range_lat_vars <- c(mean(df$lat_pchange_00_14, na.rm=T) - 2*sd(df$lat_pchange_00_14, na.rm=T),mean(df$lat_pchange_00_14, na.rm=T) + 2*sd(df$lat_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simR <- logitsimfd(mm,simbetasR,0.95)

hispDat <- data.frame(y=c(hisp_growth_simD$pe,hisp_growth_simI$pe,hisp_growth_simR$pe),
                      lower=c(hisp_growth_simD$lower,hisp_growth_simI$lower,hisp_growth_simR$lower),
                      upper=c(hisp_growth_simD$upper,hisp_growth_simI$upper,hisp_growth_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='All Whites')

# personal econ
mm <- cfChange(mmD,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

peDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='All Whites')

# economic deprived
mm <- cfChange(mmD,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

edDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='All Whites')


man_loss_range <- c(mean(df$manu_pchange_00_14, na.rm=T)-2*sd(df$manu_pchange_00_14, na.rm=T), mean(df$manu_pchange_00_14, na.rm=T)+2*sd(df$manu_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

mlDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='All Whites')

unem_context_range <- c(mean(df$unem_pchange_00_14, na.rm=T)-2*sd(df$unem_pchange_00_14, na.rm=T), mean(df$unem_pchange_00_14, na.rm=T)+2*sd(df$unem_pchange_00_14, na.rm=T)) 
mm <- cfChange(mmD,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

unemDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                      lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                      upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='All Whites')


raceVars <- rbind(antiBlack,immDat,hispDat)
raceVars$facet <- c(rep('Racial Attitudes',3),
                    rep('Immigration Attitudes',3),
                    rep('Latino Growth', 3))
raceVars$facet <- factor(raceVars$facet, levels=c('Racial Attitudes','Immigration Attitudes','Latino Growth'))


econVars <- rbind(peDat,edDat,mlDat,unemDat)
econVars$facet <- c(rep('Personal Econ',3),
                    rep('Relative Econ Dep',3),
                    rep('Manufacturing Loss', 3),
                    rep('Change Unemployment', 3))
econVars$facet <- factor(econVars$facet, levels=c('Personal Econ','Relative Econ Dep','Manufacturing Loss','Change Unemployment'))

# Vote Switching Trump ~ WWC

form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south

subD <-  df$wwc ==1 & df$pid3factor=='Democrat' &  df$vote_romney == 0 & df$voted_2012 == 1
subI <- df$wwc ==1 & df$pid3factor=='Independent' & df$vote_romney == 0 & df$voted_2012 == 1
subR <-  df$wwc ==1 & df$pid3factor=='Republican' & df$vote_romney == 0 & df$voted_2012 == 1

# Democrats

summary (trump_shift2 <-  glm(form, data = df[subD,], family="binomial"))
pe <- coef(trump_shift2)
vc <- vcov(trump_shift2)
simbetasD <- mvrnorm(1000,pe,vc)

# Independents

summary (trump_shift_i2 <-  glm(form,data = df[subI,], family="binomial") )
pe <- coef(trump_shift_i2)
vc <- vcov(trump_shift_i2)
simbetasI <- mvrnorm(1000,pe,vc)

#Republicans

summary (trump_shift_r2 <-  glm(form,data = df[subR,], family="binomial") )
pe <- coef(trump_shift_r2)
vc <- vcov(trump_shift_r2)
simbetasR <- mvrnorm(1000,pe,vc)

# Counterfactuals

mmD <- cfMake(form,df[subD,],1)
mmI <- cfMake(form,df[subI,],1)
mmR <- cfMake(form,df[subR,],1)

#anti-black attitudes

mm <- cfChange(mmD,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
antiBlack <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                        lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                        upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                        Party=c('Democrat','Independent','Republican'),
                        Group="WWC")

#imm attitudes
mm <- cfChange(mmD,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
immDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                     lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                     upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                     Party=c('Democrat','Independent','Republican'),
                     Group="WWC")

#latgrowth
range_lat_vars <- c(mean(df$lat_pchange_00_14, na.rm=T) - 2*sd(df$lat_pchange_00_14, na.rm=T),mean(df$lat_pchange_00_14, na.rm=T) + 2*sd(df$lat_pchange_00_14, na.rm=T))
range_lat_vars <- c(min(df$lat_pchange_00_14, na.rm=T),max(df$lat_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simR <- logitsimfd(mm,simbetasR,0.95)
hispDat <- data.frame(y=c(hisp_growth_simD$pe,hisp_growth_simI$pe,hisp_growth_simR$pe),
                      lower=c(hisp_growth_simD$lower,hisp_growth_simI$lower,hisp_growth_simR$lower),
                      upper=c(hisp_growth_simD$upper,hisp_growth_simI$upper,hisp_growth_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='WWC')

#personal econ

mm <- cfChange(mmD,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

peDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='WWC')

#economic deprived
mm <- cfChange(mmD,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

edDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='WWC')


man_loss_range <- c(mean(df$manu_pchange_00_14, na.rm=T)-2*sd(df$manu_pchange_00_14, na.rm=T), mean(df$manu_pchange_00_14, na.rm=T)+2*sd(df$manu_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

mlDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='WWC')

unem_context_range <- c(mean(df$unem_pchange_00_14, na.rm=T)-2*sd(df$unem_pchange_00_14, na.rm=T), mean(df$unem_pchange_00_14, na.rm=T)+2*sd(df$unem_pchange_00_14, na.rm=T)) 
mm <- cfChange(mmD,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1:10)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1:10)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1:10)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

unemDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                      lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                      upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='WWC')


raceVars2 <- rbind(antiBlack,immDat,hispDat)
raceVars2$facet <- c(rep('Racial Attitudes',3),
                     rep('Immigration Attitudes',3),
                     rep('Latino Growth', 3))
raceVars2$facet <- factor(raceVars2$facet, levels=c('Racial Attitudes','Immigration Attitudes','Latino Growth'))


econVars2 <- rbind(peDat,edDat,mlDat,unemDat)
econVars2$facet <- c(rep('Personal Econ',3),
                     rep('Relative Econ Dep',3),
                     rep('Manufacturing Loss', 3),
                     rep('Change Unemployment', 3))
econVars2$facet <- factor(econVars2$facet, levels=c('Personal Econ','Relative Econ Dep','Manufacturing Loss','Change Unemployment'))

# Vote Switching Trump ~ College Whites

form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south 


subD <-  df$wwc ==0 &  df$white_anglo == 1 &  df$pid3factor=='Democrat' &  df$vote_romney == 0 & df$voted_2012 == 1
subI <- df$wwc ==0 & df$white_anglo == 1 & df$pid3factor=='Independent' & df$vote_romney == 0 & df$voted_2012 == 1
subR <-  df$wwc ==0 & df$white_anglo == 1 & df$pid3factor=='Republican' & df$vote_romney == 0 & df$voted_2012 == 1

# Democrats

summary (trump_shift3 <-  glm(form, data = df[subD,], family="binomial"))
pe <- coef(trump_shift3)
vc <- vcov(trump_shift3)
simbetasD <- mvrnorm(1000,pe,vc)

# Independents

summary (trump_shift_i3 <-  glm(form,data = df[subI,], family="binomial") )
pe <- coef(trump_shift_i3)
vc <- vcov(trump_shift_i3)
simbetasI <- mvrnorm(1000,pe,vc)

# Republicans

summary (trump_shift_r3 <-  glm(form,data = df[subR,], family="binomial") )
pe <- coef(trump_shift_r3)
vc <- vcov(trump_shift_r3)
simbetasR <- mvrnorm(1000,pe,vc)

# Counterfactuals

mmD <- cfMake(form,df[subD,],1)
mmI <- cfMake(form,df[subI,],1)
mmR <- cfMake(form,df[subR,],1)

#anti-black attitudes

mm <- cfChange(mmD,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
antiBlack <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                        lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                        upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                        Party=c('Democrat','Independent','Republican'),
                        Group="Non-WC Whites")

#imm attitudes
mm <- cfChange(mmD,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
immDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                     lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                     upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                     Party=c('Democrat','Independent','Republican'),
                     Group="Non-WC Whites")

#latgrowth
range_lat_vars <- c(mean(df$lat_pchange_00_14, na.rm=T) - 2*sd(df$lat_pchange_00_14, na.rm=T),mean(df$lat_pchange_00_14, na.rm=T) + 2*sd(df$lat_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'lat_pchange_00_14',xpre=range_lat_vars[1],x=range_lat_vars[2],scen=1)
hisp_growth_simR <- logitsimfd(mm,simbetasR,0.95)

hispDat <- data.frame(y=c(hisp_growth_simD$pe,hisp_growth_simI$pe,hisp_growth_simR$pe),
                      lower=c(hisp_growth_simD$lower,hisp_growth_simI$lower,hisp_growth_simR$lower),
                      upper=c(hisp_growth_simD$upper,hisp_growth_simI$upper,hisp_growth_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='Non-WC Whites')

#personal econ

mm <- cfChange(mmD,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'personal_econ_worse',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

peDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='Non-WC Whites')

#economic deprived
mm <- cfChange(mmD,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'relative_deprivate',xpre=0,x=1,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

edDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='Non-WC Whites')

# man change
man_loss_range <- c(mean(df$manu_pchange_00_14, na.rm=T)-2*sd(df$manu_pchange_00_14, na.rm=T), mean(df$manu_pchange_00_14, na.rm=T)+2*sd(df$manu_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'manu_pchange_00_14',xpre=man_loss_range[1],x=man_loss_range[2],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

mlDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='Non-WC Whites')

#unem change
unem_context_range <- c(mean(df$unem_pchange_00_14, na.rm=T)-2*sd(df$unem_pchange_00_14, na.rm=T), mean(df$unem_pchange_00_14, na.rm=T)+2*sd(df$unem_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'unem_pchange_00_14',xpre=unem_context_range[1],x=unem_context_range[2],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

unemDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                      lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                      upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='Non-WC Whites')


raceVars3 <- rbind(antiBlack,immDat,hispDat)
raceVars3$facet <- c(rep('Racial Attitudes',3),
                     rep('Immigration Attitudes',3),
                     rep('Latino Growth', 3))
raceVars3$facet <- factor(raceVars3$facet, levels=c('Racial Attitudes','Immigration Attitudes','Latino Growth'))


econVars3 <- rbind(peDat,edDat,mlDat,unemDat)
econVars3$facet <- c(rep('Personal Econ',3),
                     rep('Relative Econ Dep',3),
                     rep('Manufacturing Loss', 3),
                     rep('Change Unemployment', 3))
econVars3$facet <- factor(econVars3$facet, levels=c('Personal Econ','Relative Econ Dep','Manufacturing Loss','Change Unemployment'))

# create Table 1

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","College", "Constant")
col_labs <- c("Dem (All Whites)", "Ind (All Whites)", "GOP All Whites)",
              "Dem (WWC)", "Ind (WWC)", "GOP (WWC)",
              "Dem (Non-WWC)", "Ind (Non-WWC)", "GOP (Non-WWC)")
tit <- "Predictors of Shifting to Trump in 2016"
stargazer(trump_shift, trump_shift_i, trump_shift_r,
          trump_shift2, trump_shift_i2, trump_shift_r2,
          trump_shift3, trump_shift_i3, trump_shift_r3,
          covariate.labels = cov_labs,
          omit=c('income_r', 'personal_unemployed', 'fb_pchange_00_14', 'union_comb','female','ideo_lib_cons','south'),
          column.labels=col_labs, 
          title=tit,
          label="trump_model",
          type = 'html',
          dep.var.labels = 'Trump Switch',
          out='table2.html',single.row = T,
          star.cutoffs = c(0.05, 0.01, 0.001))
stargazer(trump_shift, trump_shift_i, trump_shift_r,
          trump_shift2, trump_shift_i2, trump_shift_r2,
          trump_shift3, trump_shift_i3, trump_shift_r3,
          covariate.labels = cov_labs,
          column.labels=col_labs, 
          title=tit,
          label="trump_model",
          type = 'html',
          dep.var.labels = 'Trump Switch',
          out='tableH1.html',single.row = T,
          star.cutoffs = c(0.05, 0.01, 0.001))

g.race.out <- rbind(raceVars, raceVars2, raceVars3) %>%
  ggplot(aes(Party,y, shape=Group)) + 
  geom_hline(yintercept=0,linetype=2, color='grey') +
  geom_errorbar(aes(x=Party,ymin=lower,ymax=upper),width=.05, position=position_dodge(.3)) +
  geom_point(size=2, fill='white',position=position_dodge(.3)) + 
  scale_shape_manual(values=c(21,24,22),name='Sample') +
  labs(x='',y='Change Prob New Trump Voter | Party',title='') +
  facet_wrap(~facet) +
  theme_bw()

g.econ.out <- rbind(econVars, econVars2,econVars3) %>%
  ggplot(aes(Party,y, shape=Group)) + 
  geom_hline(yintercept=0,linetype=2, color='grey') +
  geom_errorbar(aes(x=Party,ymin=lower,ymax=upper),width=.05, position=position_dodge(.3)) +
  geom_point(size=2, fill='white',position=position_dodge(.3)) + 
  scale_shape_manual(values=c(21,24,22),name='Sample') +
  labs(x='',y='Change Prob New Trump Voter | Party',title='') +
  facet_wrap(~facet) +
  theme_bw()

ggsave(g.race.out,width=10,height=5,file='figure1.eps')
ggsave(g.econ.out,width=8,height=6,file='figure3.eps')


# Table 3, Figure 2 and Figure 4 -----------------------------------------------------------------
# Vote Switching Clinton ~ all whites

# formula
form_vote_shift_clinton <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college

# subsets
subD <- df$white_anglo ==1 & df$pid3factor=='Democrat' & df$vote_obama==0 & df$voted_2012 == 1
subI <- df$white_anglo ==1 & df$pid3factor=='Independent' & df$vote_obama==0 & df$voted_2012 == 1
subR <- df$white_anglo ==1 & df$pid3factor=='Republican' & df$vote_obama==0 & df$voted_2012 == 1

# models

summary (cshift <-  glm(form_vote_shift_clinton, data = df[subD,], family="binomial"))
summary (cshift_i <-  glm(form_vote_shift_clinton,data = df[subI,], family="binomial") )
summary (cshift_r <-  glm(form_vote_shift_clinton,data = df[subR,], family="binomial") )

pe <- coef(cshift)
vc <- vcov(cshift)
simbetasD <- mvrnorm(1000,pe,vc)
pe <- coef(cshift_i)
vc <- vcov(cshift_i)
simbetasI <- mvrnorm(1000,pe,vc)
pe <- coef(cshift_r)
vc <- vcov(cshift_r)
simbetasR <- mvrnorm(1000,pe,vc)

mmD <- cfMake(form_vote_shift_clinton,df[subD,],1)
mmI <- cfMake(form_vote_shift_clinton,df[subI,],1)
mmR <- cfMake(form_vote_shift_clinton,df[subR,],1)

#anti-black attitudes
mm <- cfChange(mmD,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
antiBlack <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                        lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                        upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                        Party=c('Democrat','Independent','Republican'),
                        Group="All Whites")

#imm attitudes
mm <- cfChange(mmD,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
immDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                     lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                     upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                     Party=c('Democrat','Independent','Republican'),
                     Group="All Whites")


#personal econ
mm <- cfChange(mmD,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

peDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='All Whites')

#economic deprived
mm <- cfChange(mmD,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

edDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='All Whites')


man_loss_range <- c(min(df$manu_pchange_00_14, na.rm=T)-2*sd(df$manu_pchange_00_14, na.rm=T), mean(df$manu_pchange_00_14, na.rm=T)+2*sd(df$manu_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

mlDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='All Whites')

unem_context_range <- c(mean(df$unem_pchange_00_14, na.rm=T)-2*sd(df$unem_pchange_00_14, na.rm=T), mean(df$unem_pchange_00_14, na.rm=T)+2*sd(df$unem_pchange_00_14, na.rm=T)) 
mm <- cfChange(mmD,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

unemDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                      lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                      upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='All Whites')


raceVars <- rbind(antiBlack,immDat)
raceVars$facet <- c(rep('Racial Attitudes',3),
                    rep('Immigration Attitudes',3))
raceVars$facet <- factor(raceVars$facet, levels=c('Racial Attitudes','Immigration Attitudes'))


econVars <- rbind(peDat,edDat,mlDat,unemDat)
econVars$facet <- c(rep('Personal Econ',3),
                    rep('Relative Econ Dep',3),
                    rep('Manufacturing Loss', 3),
                    rep('Change Unemployment', 3))
econVars$facet <- factor(econVars$facet, levels=c('Personal Econ','Relative Econ Dep','Manufacturing Loss','Change Unemployment'))

# Just WWC/Clinton ----

# formula
form_vote_shift_clinton <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south

# subsets
subD <-  df$wwc ==1 & df$pid3factor=='Democrat' &  df$vote_obama == 0 & df$voted_2012 == 1
subI <- df$wwc ==1 & df$pid3factor=='Independent' & df$vote_obama == 0 & df$voted_2012 == 1
subR <-  df$wwc ==1 & df$pid3factor=='Republican' & df$vote_obama == 0 & df$voted_2012 == 1

# run models
summary (cshift2 <-  glm(form_vote_shift_clinton, data = df[subD,], family="binomial"))
summary (cshift_i2 <-  glm(form_vote_shift_clinton,data = df[subI,], family="binomial") )
summary (cshift_r2 <-  glm(form_vote_shift_clinton,data = df[subR,], family="binomial") )

pe <- coef(cshift2)
vc <- vcov(cshift2)
simbetasD <- mvrnorm(1000,pe,vc)
pe <- coef(cshift_i2)
vc <- vcov(cshift_i2)
simbetasI <- mvrnorm(1000,pe,vc)
pe <- coef(cshift_r2)
vc <- vcov(cshift_r2)
simbetasR <- mvrnorm(1000,pe,vc)

mmD <- cfMake(form_vote_shift_clinton,df[subD,],1)
mmI <- cfMake(form_vote_shift_clinton,df[subI,],1)
mmR <- cfMake(form_vote_shift_clinton,df[subR,],1)

#anti-black attitudes

mm <- cfChange(mmD,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
antiBlack <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                        lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                        upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                        Party=c('Democrat','Independent','Republican'),
                        Group="WWC")

#imm attitudes
mm <- cfChange(mmD,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
immDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                     lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                     upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                     Party=c('Democrat','Independent','Republican'),
                     Group="WWC")

#personal econ

mm <- cfChange(mmD,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

peDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='WWC')

#economic deprived
mm <- cfChange(mmD,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

edDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='WWC')


man_loss_range <- c(min(df$manu_pchange_00_14, na.rm=T)-2*sd(df$manu_pchange_00_14, na.rm=T), mean(df$manu_pchange_00_14, na.rm=T)+2*sd(df$manu_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

mlDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='WWC')

unem_context_range <- c(mean(df$unem_pchange_00_14, na.rm=T)-2*sd(df$unem_pchange_00_14, na.rm=T), mean(df$unem_pchange_00_14, na.rm=T)+2*sd(df$unem_pchange_00_14, na.rm=T)) 
mm <- cfChange(mmD,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

unemDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                      lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                      upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='WWC')


raceVars2 <- rbind(antiBlack,immDat)
raceVars2$facet <- c(rep('Racial Attitudes',3),
                     rep('Immigration Attitudes',3))
raceVars2$facet <- factor(raceVars2$facet, levels=c('Racial Attitudes','Immigration Attitudes'))


econVars2 <- rbind(peDat,edDat,mlDat,unemDat)
econVars2$facet <- c(rep('Personal Econ',3),
                     rep('Relative Econ Dep',3),
                     rep('Manufacturing Loss', 3),
                     rep('Change Unemployment', 3))
econVars2$facet <- factor(econVars2$facet, levels=c('Personal Econ','Relative Econ Dep','Manufacturing Loss','Change Unemployment'))

# College whites/Clinton ----

# formula
form_vote_shift_clinton <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south

# subsets
subD <-  df$wwc ==0 &  df$white_anglo == 1 &  df$pid3factor=='Democrat' &  df$vote_obama == 0 & df$voted_2012 == 1
subI <- df$wwc ==0 & df$white_anglo == 1 & df$pid3factor=='Independent' & df$vote_obama == 0 & df$voted_2012 == 1
subR <-  df$wwc ==0 & df$white_anglo == 1 & df$pid3factor=='Republican' & df$vote_obama == 0 & df$voted_2012 == 1


# run models
summary (cshift3 <-  glm(form_vote_shift_clinton, data = df[subD,], family="binomial"))
summary (cshift_i3 <-  glm(form_vote_shift_clinton,data = df[subI,], family="binomial") )
summary (cshift_r3 <-  glm(form_vote_shift_clinton,data = df[subR,], family="binomial") )

pe <- coef(cshift3)
vc <- vcov(cshift3)
simbetasD <- mvrnorm(1000,pe,vc)
pe <- coef(cshift_i3)
vc <- vcov(cshift_i3)
simbetasI <- mvrnorm(1000,pe,vc)
pe <- coef(cshift_r3)
vc <- vcov(cshift_r3)
simbetasR <- mvrnorm(1000,pe,vc)

mmD <- cfMake(form_vote_shift_clinton,df[subD,],1)
mmI <- cfMake(form_vote_shift_clinton,df[subI,],1)
mmR <- cfMake(form_vote_shift_clinton,df[subR,],1)

#anti-black attitudes

mm <- cfChange(mmD,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'race_attitudes',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
antiBlack <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                        lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                        upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                        Party=c('Democrat','Independent','Republican'),
                        Group="Non-WC Whites")

#imm attitudes
mm <- cfChange(mmD,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmI,'anti_scale',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)
immDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                     lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                     upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                     Party=c('Democrat','Independent','Republican'),
                     Group="Non-WC Whites")

#personal econ

mm <- cfChange(mmD,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'personal_econ_worse',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

peDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='Non-WC Whites')

#economic deprived
mm <- cfChange(mmD,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'relative_deprivate',xpre=1,x=0,scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

edDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='Non-WC Whites')


man_loss_range <- c(min(df$manu_pchange_00_14, na.rm=T)-2*sd(df$manu_pchange_00_14, na.rm=T), mean(df$manu_pchange_00_14, na.rm=T)+2*sd(df$manu_pchange_00_14, na.rm=T))
mm <- cfChange(mmD,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'manu_pchange_00_14',xpre=man_loss_range[2],x=man_loss_range[1],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

mlDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                    lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                    upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                    Party=c('Democrat','Independent','Republican'),
                    Group='Non-WC Whites')

unem_context_range <- c(mean(df$unem_pchange_00_14, na.rm=T)-2*sd(df$unem_pchange_00_14, na.rm=T), mean(df$unem_pchange_00_14, na.rm=T)+2*sd(df$unem_pchange_00_14, na.rm=T)) 
mm <- cfChange(mmD,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simD <- logitsimfd(mm,simbetasD,0.95)
mm <- cfChange(mmI,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simI <- logitsimfd(mm,simbetasI,0.95)
mm <- cfChange(mmR,'unem_pchange_00_14',xpre=unem_context_range[2],x=unem_context_range[1],scen=1)
anti_scale_simR <- logitsimfd(mm,simbetasR,0.95)

unemDat <- data.frame(y=c(anti_scale_simD$pe,anti_scale_simI$pe,anti_scale_simR$pe),
                      lower=c(anti_scale_simD$lower,anti_scale_simI$lower,anti_scale_simR$lower),
                      upper=c(anti_scale_simD$upper,anti_scale_simI$upper,anti_scale_simR$upper),
                      Party=c('Democrat','Independent','Republican'),
                      Group='Non-WC Whites')


raceVars3 <- rbind(antiBlack,immDat)
raceVars3$facet <- c(rep('Racial Attitudes',3),
                     rep('Immigration Attitudes',3))
raceVars3$facet <- factor(raceVars3$facet, levels=c('Racial Attitudes','Immigration Attitudes'))


econVars3 <- rbind(peDat,edDat,mlDat,unemDat)
econVars3$facet <- c(rep('Personal Econ',3),
                     rep('Relative Econ Dep',3),
                     rep('Manufacturing Loss', 3),
                     rep('Change Unemployment', 3))
econVars3$facet <- factor(econVars3$facet, levels=c('Personal Econ','Relative Econ Dep','Manufacturing Loss','Change Unemployment'))

# Table 3

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","College", "Constant")
col_labs <- c("Dem (All Whites)", "Ind (All Whites)", "GOP (All Whites)",
              "Dem (WWC)", "Ind (WWC)", "GOP (WWC)",
              "Dem (Non-WWC)", "Ind (Non-WWC)", "GOP (Non-WWC)")
tit <- "Predictors of Shifting to Clinton in 2016"

stargazer(cshift, cshift_i, cshift_r,
          cshift2, cshift_i2, cshift_r2,
          cshift3, cshift_i3, cshift_r3,
          covariate.labels = cov_labs,
          column.labels=col_labs, title=tit, 
          omit=c('income_r', 'personal_unemployed', 'fb_pchange_00_14', 'union_comb','female','ideo_lib_cons','south'),
          label="clinton_models",type = 'html',
          dep.var.labels = 'Clinton Switch',
          out='table3.html',single.row = T,
          star.cutoffs = c(0.05, 0.01, 0.001))


stargazer(cshift, cshift_i, cshift_r,
          cshift2, cshift_i2, cshift_r2,
          cshift3, cshift_i3, cshift_r3,
          covariate.labels = cov_labs,
          column.labels=col_labs, title=tit, 
          label="clinton_models",type = 'html',
          dep.var.labels = 'Clinton Switch',
          out='tableH2.html',single.row = T,
          star.cutoffs = c(0.05, 0.01, 0.001))

# Figures 2 and 4

g.race.out <- rbind(raceVars, raceVars2, raceVars3) %>%
  ggplot(aes(Party,y, shape=Group)) + 
  geom_hline(yintercept=0,linetype=2, color='grey') +
  geom_errorbar(aes(x=Party,ymin=lower,ymax=upper),width=.05, position=position_dodge(.3)) +
  geom_point(size=2, fill='white',position=position_dodge(.3)) + 
  scale_shape_manual(values=c(21,24,22),name='Sample') +
  labs(x='',y='Change Prob New Clinton Voter | Party',title='') +
  facet_wrap(~facet) +
  theme_bw()

g.econ.out <- rbind(econVars, econVars2,econVars3) %>%
  ggplot(aes(Party,y, shape=Group)) + 
  geom_hline(yintercept=0,linetype=2, color='grey') +
  geom_errorbar(aes(x=Party,ymin=lower,ymax=upper),width=.05, position=position_dodge(.3)) +
  geom_point(size=2, fill='white',position=position_dodge(.3)) + 
  scale_shape_manual(values=c(21,24,22),name='Sample') +
  labs(x='',y='Change Prob New Clinton Voter | Party',title='') +
  facet_wrap(~facet) +
  theme_bw()

ggsave(g.race.out,width=10,height=5,file='figure2.eps')
ggsave(g.econ.out,width=8,height=6,file='figure4.eps')

# Appendix -----------------------------------------------------------------

# Table A.1: Working Class As Lower Tercile 

lower_tercile <- quantile(df$income_r,.33,na.rm=T)
form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south  + college 
subD <- df$pid3factor=='Democrat' &  df$vote_romney == 0 & df$voted_2012==1 & df$income_r <= 4 & df$white_anglo == 1
subI <- df$pid3factor=='Independent' & df$vote_romney == 0 & df$voted_2012==1 & df$income_r <= 4& df$white_anglo == 1
subR <- df$pid3factor=='Republican' & df$vote_romney == 0 & df$voted_2012==1 & df$income_r <= 4& df$white_anglo == 1
summary (trump_shift <-  glm(form, data = df[subD,], family="binomial"))
summary (trump_shift_i <-  glm(form,data = df[subI,], family="binomial") )
summary (trump_shift_r <-  glm(form,data = df[subR,], family="binomial") )
form <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south  + college 
subD <- df$pid3factor=='Democrat' &  df$vote_obama == 0 & df$voted_2012==1 & df$income_r <= 4 & df$white_anglo == 1
subI <- df$pid3factor=='Independent' & df$vote_obama == 0 & df$voted_2012==1 & df$income_r <= 4& df$white_anglo == 1
subR <- df$pid3factor=='Republican' & df$vote_obama == 0 & df$voted_2012==1 & df$income_r <= 4& df$white_anglo == 1
summary (c1 <-  glm(form, data = df[subD,], family="binomial"))
summary (c2 <-  glm(form,data = df[subI,], family="binomial") )
summary (c3 <-  glm(form,data = df[subR,], family="binomial") )
cov_labs <- c("Racial Attitudes", "Immigration Attitudes", 
              "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", 
              "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","College", "Constant")
col_labs <- c("WWC Dem", "WWC Ind", "WWC GOP","WWC Dem", "WWC Ind", "WWC GOP")
tit <- "Vote Switch: Working Class as Lower Tercile Income Distribution"
stargazer(trump_shift, trump_shift_i, trump_shift_r, 
          c1, c2, c3,
          covariate.labels = cov_labs,
          column.labels=col_labs, 
          label="wwc_vote_lowincome",
          type = 'html',
          dep.var.labels = c('Vote Switch Trump','Vote Switch Clinton'),
          out='tableA1.html',star.cutoffs = c(0.05, 0.01, 0.001))

# Table B.1: Assessing Potential Lying

dat <- read.spss('anes2008_2009panel.por',
                 to.data.frame = T)
dat$mccain_sept <- ifelse(dat$W9D2A=='1. John McCain',1,0)
dat$mccain_oct <- ifelse(dat$W10A6A=='1. John McCain',1,0)
dat$obama_nov <- ifelse(dat$W11A6=='18. BARACK OBAMA for PresidentJOE BIDEN for Vice PresidentDemocrat{InsTxt}',1,0)

## demos
dat$white <- ifelse(dat$RRACEWHI=='1. Marked',1,0)
dat$college <- ifelse(dat$DER05 %in% c("4. Bachelor's degree","5. Graduate degree"),1,0)
dat$black_symp <- NA
dat$black_symp[dat$W17X24=="5. Never"] <- 5
dat$black_symp[dat$W17X24=="4. Once in a while"] <- 4
dat$black_symp[dat$W17X24=="3. About half the time"] <- 3
dat$black_symp[dat$W17X24=="2. Most of the time"] <- 2
dat$black_symp[dat$W17X24=="1. Always"] <- 1
median(dat$black_symp,na.rm=T)
hist(dat$black_symp)

full <- subset(dat, white==1)
collegewhite <- subset(dat, white==1 & college == 1)
wwc <- subset(dat, white==1 & college == 0)
lowrr <- subset(dat, white==1 & black_symp < 4)
highrr <- subset(dat, white==1 & black_symp >= 4)

dat <- data.frame(x=c('All Whites','College Whites','WWC','Low RR','High RR'),
                  y=c(weighted.mean(full$obama_nov==1 & full$mccain_oct==1,na.rm=T,w=full$WGTBASE),
                      weighted.mean(collegewhite$obama_nov==1 & collegewhite$mccain_oct==1,na.rm=T,w=collegewhite$WGTBASE),
                      weighted.mean(wwc$obama_nov==1 & wwc$mccain_oct==1,na.rm=T,w=wwc$WGTBASE),
                      weighted.mean(lowrr$obama_nov==1 & lowrr$mccain_oct==1,na.rm=T,w=lowrr$WGTBASE),
                      weighted.mean(highrr$obama_nov==1 & highrr$mccain_oct==1,na.rm=T,w=highrr$WGTBASE)))
dat$x <- factor(dat$x, levels=rev(dat$x))
dat$y <- dat$y * 100
dat

# Table C.1: Pooled Models

form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 &  df$vote_romney == 0 & df$voted_2012 == 1
trump_shift_all <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 &  df$vote_romney == 0 & df$voted_2012 == 1
trump_shift_wwc <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 &  df$vote_romney == 0 & df$voted_2012 == 1
trump_shift_otherwhite <-  glm(form, data = df[subAll,], family="binomial")

form_vote_shift_clinton <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 &  df$vote_romney == 0 & df$voted_2012 == 1
cshift <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 &  df$vote_romney == 0 & df$voted_2012 == 1
cshift_wwc <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 &  df$vote_romney == 0 & df$voted_2012 == 1
cshift_otherwhite <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","Partisanship (R)","College", "Constant")

col_labs <- c("Trump All", "Trump WWC", "Trump Non-WWC",
              "Clinton All", "Clinton WWC", "Clinton Non-WWC")
tit <- "Full Model Pooled Across Partisan Categories"
stargazer(trump_shift_all, trump_shift_wwc, trump_shift_otherwhite,
          cshift, cshift_wwc, cshift_otherwhite,
          column.labels=col_labs, covariate.labels = cov_labs,
          label="",
          type = 'html',
          dep.var.labels = '',
          out='tablec1.html',star.cutoffs = c(0.05, 0.01, 0.001))


# Figures Appendix D.1 through Appendix D.7

g.out <- df %>%
  filter(white_anglo==1) %>%
  dplyr::select(personal_econ_worse) %>%
  na.omit() %>% 
  ggplot(aes(personal_econ_worse)) + 
  geom_histogram(color='black',fill='white',bins=5) +
  scale_x_continuous(breaks=c(0,.25,.5,.75,1)) +
  theme_bw() +  labs(y='',x='Retrospective Economic Evaluations \n(better to worst)')
g.out
ggsave(g.out,file="figured4.eps",height=2.5,width=6)

g.out <- df %>%
  filter(white_anglo==1) %>%
  dplyr::select(manu_pchange_00_14) %>%
  na.omit() %>%
  ggplot(aes(manu_pchange_00_14)) + 
  geom_histogram(color='black',fill='white',bins=20) +
  theme_bw() +
  labs(y='',x='Pct Change County Manufacturing \n2000-2014')
ggsave(g.out,file="figured6.eps",height=2.5,width=6)

g.out <- df %>%
  filter(white_anglo==1) %>%
  dplyr::select(unem_pchange_00_14) %>%
  na.omit() %>%
  ggplot(aes(unem_pchange_00_14)) + geom_histogram(color='black',fill='white',bins=20) +
  theme_bw() +
  labs(y='',x='Pct Change in County Unemployment \n2000-2014')
ggsave(g.out,file="figured7.eps",height=2.5,width=6)

g.out <- df %>%
  filter(white_anglo==1) %>%
  dplyr::select(relative_deprivate) %>%
  na.omit() %>%
  ggplot(aes(relative_deprivate)) + geom_histogram(color='black',fill='white',bins=2) +
  theme_bw() +
  labs(y='',x='Relative Deprivation')
ggsave(g.out,file="figured5.eps",height=2.5,width=6)

g.out <- df %>%
  filter(white_anglo==1) %>%
  dplyr::select(lat_pchange_00_14) %>%
  na.omit() %>%
  ggplot(aes(lat_pchange_00_14)) + geom_histogram(color='black',fill='white') +
  scale_x_continuous(limits=c(-100,500)) +
  labs(x="Latino County Growth \n(low to high)",y='') +
  theme_bw()
ggsave(g.out,file="figured3.eps",height=2.5,width=6)

g.out <- df %>%
  filter(white_anglo==1) %>%
  dplyr::select(anti_scale) %>%
  na.omit() %>%
  ggplot(aes(anti_scale)) + geom_histogram(binwidth=0.25,color='black',fill='white') +
  scale_x_continuous(breaks=c(0,.25,.5,.75,1)) +
  labs(x="Immigration Attitudes Scale \n(Pro- to Anti-)",y='') +
  theme_bw()
ggsave(g.out,file="figured2.eps",height=2.5,width=6)


g.out <- df %>%
  filter(white_anglo==1) %>%
  dplyr::select(race_attitudes) %>%
  na.omit() %>%
  ggplot(aes(race_attitudes)) + geom_histogram(binwidth=0.25,color='black',fill='white') +
  scale_x_continuous(breaks=c(0,.25,.5,.75,1)) +
  labs(x="Racial Attitudes Scale \n(Liberal to Conservative)",y='') +
  theme_bw()
ggsave(g.out,file="figured1.eps",height=2.5,width=6)

# Appendix E Table 1: Disaggregating Race and Immigration Scales

form <- vote_trump ~ 
  r1 + r2 + r3 + 
  deport_illegals + dont_grant_legal_status + increase_border_patrol + no_dreamer +
  lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college

subD <-  df$white_anglo ==1 & df$pid3factor=='Democrat' &  df$vote_romney == 0 & df$voted_2012 == 1
subI <- df$white_anglo ==1 & df$pid3factor=='Independent' & df$vote_romney == 0 & df$voted_2012 == 1
subR <-  df$white_anglo ==1 & df$pid3factor=='Republican' & df$vote_romney == 0 & df$voted_2012 == 1

summary (t1 <-  glm(form, data = df[subD,], family="binomial"))
summary (t2 <-  glm(form,data = df[subI,], family="binomial") )
summary (t3 <-  glm(form,data = df[subR,], family="binomial") )

form_vote_shift_clinton <- vote_clinton ~ 
  r1 + r2 + r3 + 
  deport_illegals + dont_grant_legal_status + increase_border_patrol + no_dreamer +
  lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college

subD <- df$white_anglo == 1 &  df$pid3factor=='Democrat' &  df$vote_obama == 0 & df$voted_2012 == 1
subI <- df$white_anglo == 1 & df$pid3factor=='Independent' & df$vote_obama == 0 & df$voted_2012 == 1
subR <-  df$white_anglo == 1 & df$pid3factor=='Republican' & df$vote_obama == 0 & df$voted_2012 == 1

summary (c1 <-  glm(form_vote_shift_clinton, data = df[subD,], family="binomial"))
summary (c2 <-  glm(form_vote_shift_clinton,data = df[subI,], family="binomial") )
summary (c3 <-  glm(form_vote_shift_clinton,data = df[subR,], family="binomial") )

cov_labs <- c("Not Angry Racism Exists","Whites Don't Have Advantages","Racial Problems are Rare",
              "Deport Undocumented", "Don't Grant Legal Status", "Increase Border Patrol", "No Dream Act",
              "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation",
              "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","College", "Constant")
col_labs <- c("Dem", "Ind", "Rep","Dem", "Ind", "Rep")
stargazer(t1, t2, t3, 
          c1,c2,c3,
          covariate.labels = cov_labs,
          column.labels=col_labs, 
          label="disagg_scale",
          type = 'html',
          dep.var.labels = c('Vote Switch Trump', 'Vote Switch Clinton'),
          out='tableE1.html',star.cutoffs = c(0.05, 0.01, 0.001))

# Table Appendix F 1: Different Time Spans Change Measures

df$manu_pchange_10_14 <- ((df$pct_manufacturing_14 - df$pct_manufacturing_10)/df$pct_manufacturing_10)*100
df$manu_pchange_10_14[!is.finite(df$manu_pchange_10_14)] <- NA
df$unem_pchange_10_14 <- ((df$pct_unemployed_14 - df$pct_unemployed_10)/df$pct_unemployed_10)*100
df$unem_pchange_10_14[!is.finite(df$unem_pchange_10_14)] <- NA

df$manu_pchange_14_16 <- ((df$pct_manufacturing_16 - df$pct_manufacturing_14)/df$pct_manufacturing_14)*100
df$manu_pchange_14_16[!is.finite(df$manu_pchange_14_16)] <- NA
df$unem_pchange_14_16 <- ((df$pct_unemployed_16 - df$pct_unemployed_14)/df$pct_unemployed_14)*100
df$unem_pchange_14_16[!is.finite(df$unem_pchange_14_16)] <- NA

form1 <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college
form2 <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_10_14 + unem_pchange_10_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college
form3 <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_14_16 + unem_pchange_14_16 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college

sub <-  df$white_anglo ==1 &  df$vote_romney == 0 & df$voted_2012 == 1

t1 <-  glm(form1, data = df[sub,], family="binomial")
t2 <-  glm(form2, data = df[sub,], family="binomial")
t3 <-  glm(form3, data = df[sub,], family="binomial")

form1 <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college
form2 <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_10_14 + unem_pchange_10_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college
form3 <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_14_16 + unem_pchange_14_16 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college

sub <- df$white_anglo ==1 & df$vote_obama==0 & df$voted_2012 == 1

c1 <-  glm(form1, data = df[sub,], family="binomial")
c2 <-  glm(form2, data = df[sub,], family="binomial")
c3 <-  glm(form3, data = df[sub,], family="binomial")

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation",
              "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Pct. Manufacturing Loss (10-14)","Pct. Unemployment Diff (10-14)",
              "Pct. Manufacturing Loss (14-16)","Pct. Unemployment Diff (14-16)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","College", "Constant")
col_labs <- c("00-14", "10-14", "14-16","00-14", "10-14", "14-16")
stargazer(t1, t2, t3, 
          c1,c2,c3,
          covariate.labels = cov_labs,
          column.labels=col_labs, 
          label="wwc_diff",
          type = 'html',
          dep.var.labels = c('Vote Switch Trump', 'Vote Switch Clinton'),
          out='tableF1.html',star.cutoffs = c(0.05, 0.01, 0.001))


# Table Appendix H 1: Multiple Imputation

#extract variable names
allVars <-  as.character(expression(vote_trump,vote_clinton, race_attitudes, anti_scale, 
                                    lat_pchange_00_14, personal_econ_worse,
                                    relative_deprivate,manu_pchange_00_14,
                                    unem_pchange_00_14,income_r,
                                    personal_unemployed,fb_pchange_00_14,union_comb,
                                    female,ideo_lib_cons,south,college,white_anglo,
                                    pid3factor,vote_obama,vote_romney,voted_2012))

rawImputeData <- df[,allVars]
imputedVars <- as.character(expression(race_attitudes, anti_scale, 
                                       lat_pchange_00_14, personal_econ_worse,
                                       relative_deprivate,manu_pchange_00_14,
                                       unem_pchange_00_14,income_r,
                                       personal_unemployed,fb_pchange_00_14,union_comb,
                                       female,ideo_lib_cons,south,college))

#create predictor matrix
predictorMatrix <- matrix(0, ncol = length(allVars), nrow = length(allVars))
rownames(predictorMatrix) <- allVars
colnames(predictorMatrix) <- allVars

#variables to use to inform predictions
predictorMatrix[,imputedVars] <- 1
#variable we don't want to impute
diag(predictorMatrix) <- 0 #make diagonals zeros
predictorMatrix

#dry run
dryMice <- mice(data = rawImputeData, m = 1, predictorMatrix = predictorMatrix, maxit = 0)
dryMice$method[1:2] <- ''

# need to impute age, edu, eth, and inc, not gender
# note that this takes about an hour to run
sub_survey_impute <- mice(rawImputeData, m = 5, maxit = 10, 
                          predictorMatrix = predictorMatrix,
                          seed = 12345, method = dryMice$method)

#miceadds::write.mice.imputation(mi.res=sub_survey_impute , name="imputed_datasets.csv")

# create imputationList datasets
imputed_data <- imputationList(
  lapply(1:sub_survey_impute$m, 
         function(i) complete(sub_survey_impute, i))
)

#dem models; n = 687
apply(imputed_data$imputations[[1]],2, function(x) table(is.na(x)))
table(imputed_data$imputations[[1]]$white_anglo == 1 & 
        imputed_data$imputations[[1]]$pid3factor == 'Democrat' & 
        imputed_data$imputations[[1]]$vote_obama == 0 & 
        imputed_data$imputations[[1]]$voted_2012 == 1, useNA='ifany')
dem_imp <- miceadds::subset_datlist( imputed_data , index = 1:5 , 
                                     subset = imputed_data$imputations[[1]]$white_anglo == 1 & 
                                       imputed_data$imputations[[1]]$pid3factor == 'Democrat' & 
                                       imputed_data$imputations[[1]]$vote_obama == 0 & 
                                       imputed_data$imputations[[1]]$voted_2012 == 1 & 
                                       !is.na(imputed_data$imputations[[1]]$vote_trump) &
                                       !is.na(imputed_data$imputations[[1]]$vote_clinton) &
                                       !is.na(imputed_data$imputations[[1]]$pid3factor))
demOut <- MIcombine(with(dem_imp, glm(vote_trump~ race_attitudes + anti_scale + lat_pchange_00_14 +
                                        personal_econ_worse + relative_deprivate + 
                                        manu_pchange_00_14 + unem_pchange_00_14 +
                                        income_r + personal_unemployed + fb_pchange_00_14 + 
                                        union_comb + female +  ideo_lib_cons + south + college, family=binomial(link='logit'))))

#ind models; n = 6998
ind_imp <- miceadds::subset_datlist( imputed_data , index = 1:5 , 
                                     subset = imputed_data$imputations[[1]]$white_anglo == 1 & 
                                       imputed_data$imputations[[1]]$pid3factor == 'Independent' & 
                                       imputed_data$imputations[[1]]$vote_obama == 0 & 
                                       imputed_data$imputations[[1]]$voted_2012 == 1 & 
                                       !is.na(imputed_data$imputations[[1]]$vote_trump) &
                                       !is.na(imputed_data$imputations[[1]]$vote_clinton) &
                                       !is.na(imputed_data$imputations[[1]]$pid3factor))
indOut <- MIcombine(with(ind_imp, glm(vote_trump~ race_attitudes + anti_scale + lat_pchange_00_14 +
                                        personal_econ_worse + relative_deprivate + 
                                        manu_pchange_00_14 + unem_pchange_00_14 +
                                        income_r + personal_unemployed + fb_pchange_00_14 + 
                                        union_comb + female +  ideo_lib_cons + south + college, family=binomial(link='logit'))))

#rep models; n = 9802
rep_imp <- miceadds::subset_datlist( imputed_data , index = 1:5 , 
                                     subset = imputed_data$imputations[[1]]$white_anglo == 1 & 
                                       imputed_data$imputations[[1]]$pid3factor == 'Republican' & 
                                       imputed_data$imputations[[1]]$vote_obama == 0 & 
                                       imputed_data$imputations[[1]]$voted_2012 == 1 & 
                                       !is.na(imputed_data$imputations[[1]]$vote_trump) &
                                       !is.na(imputed_data$imputations[[1]]$vote_clinton) &
                                       !is.na(imputed_data$imputations[[1]]$pid3factor))
repOut <- MIcombine(with(rep_imp, glm(vote_trump~ race_attitudes + anti_scale + lat_pchange_00_14 +
                                        personal_econ_worse + relative_deprivate + 
                                        manu_pchange_00_14 + unem_pchange_00_14 +
                                        income_r + personal_unemployed + fb_pchange_00_14 + 
                                        union_comb + female +  ideo_lib_cons + south + college, family=binomial(link='logit'))))


####
# n = 11400
dem_imp <- miceadds::subset_datlist( imputed_data , index = 1:5 , 
                                     subset = imputed_data$imputations[[1]]$white_anglo == 1 & 
                                       imputed_data$imputations[[1]]$pid3factor == 'Democrat' & 
                                       imputed_data$imputations[[1]]$vote_romney == 0 & 
                                       imputed_data$imputations[[1]]$voted_2012 == 1& 
                                       !is.na(imputed_data$imputations[[1]]$vote_trump) &
                                       !is.na(imputed_data$imputations[[1]]$vote_clinton) &
                                       !is.na(imputed_data$imputations[[1]]$pid3factor) )
demOut2 <- MIcombine(with(dem_imp, glm(vote_clinton~ race_attitudes + anti_scale + lat_pchange_00_14 +
                                         personal_econ_worse + relative_deprivate + 
                                         manu_pchange_00_14 + unem_pchange_00_14 +
                                         income_r + personal_unemployed + fb_pchange_00_14 + 
                                         union_comb + female +  ideo_lib_cons + south + college, family=binomial(link='logit'))))

# n = 6636
ind_imp <- miceadds::subset_datlist( imputed_data , index = 1:5 , 
                                     subset = imputed_data$imputations[[1]]$white_anglo == 1 & 
                                       imputed_data$imputations[[1]]$pid3factor == 'Independent' & 
                                       imputed_data$imputations[[1]]$vote_romney == 0 & 
                                       imputed_data$imputations[[1]]$voted_2012 == 1 & 
                                       !is.na(imputed_data$imputations[[1]]$vote_trump) &
                                       !is.na(imputed_data$imputations[[1]]$vote_clinton) &
                                       !is.na(imputed_data$imputations[[1]]$pid3factor))
indOut2 <- MIcombine(out2 <- with(ind_imp, glm(vote_clinton~ race_attitudes + anti_scale + lat_pchange_00_14 +
                                                 personal_econ_worse + relative_deprivate + 
                                                 manu_pchange_00_14 + unem_pchange_00_14 +
                                                 income_r + personal_unemployed + fb_pchange_00_14 + 
                                                 union_comb + female +  ideo_lib_cons + south + college, family=binomial(link='logit'))))

# n = 1248
rep_imp <- miceadds::subset_datlist( imputed_data , index = 1:5 , 
                                     subset = imputed_data$imputations[[1]]$white_anglo == 1 & 
                                       imputed_data$imputations[[1]]$pid3factor == 'Republican' & 
                                       imputed_data$imputations[[1]]$vote_romney == 0 & 
                                       imputed_data$imputations[[1]]$voted_2012 == 1 & 
                                       !is.na(imputed_data$imputations[[1]]$vote_trump) &
                                       !is.na(imputed_data$imputations[[1]]$vote_clinton) &
                                       !is.na(imputed_data$imputations[[1]]$pid3factor))
repOut2 <- MIcombine(out <- with(rep_imp, glm(vote_clinton~ race_attitudes + anti_scale + lat_pchange_00_14 +
                                                personal_econ_worse + relative_deprivate + 
                                                manu_pchange_00_14 + unem_pchange_00_14 +
                                                income_r + personal_unemployed + fb_pchange_00_14 + 
                                                union_comb + female +  ideo_lib_cons + south + college, 
                                              family=binomial(link='logit'))))

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","College", "Constant")

star <- stargazer(coeftest(demOut),coeftest(indOut),coeftest(repOut),
                  coeftest(demOut2),coeftest(indOut2),coeftest(repOut2),
                  type='html', style='APSR',out = 'tableG1.html',
                  star.cutoffs = c(0.05, 0.01, 0.001),
                  covariate.labels=cov_labs)

# Appendix Tables H (see code for Tables 2 and 3 above): Full regression Tables ---------------

# Appendix I Figure 1: Model Fit ------------------------------------

form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college

all <-  df$white_anglo ==1 & df$vote_romney == 0 & df$voted_2012 == 1
subD <-  df$white_anglo ==1 & df$pid3factor=='Democrat' &  df$vote_romney == 0 & df$voted_2012 == 1
subI <- df$white_anglo ==1 & df$pid3factor=='Independent' & df$vote_romney == 0 & df$voted_2012 == 1
subR <-  df$white_anglo ==1 & df$pid3factor=='Republican' & df$vote_romney == 0 & df$voted_2012 == 1

trump_shift_all <-  glm(form, data = df[all,], family="binomial")
trump_shift <-  glm(form, data = df[subD,], family="binomial")
trump_shift_i <-  glm(form,data = df[subI,], family="binomial") 
trump_shift_r <-  glm(form,data = df[subR,], family="binomial") 

roc1 <- roc(trump_shift_all$model$vote_trump,trump_shift_all$fitted.values,auc = T)
roc2 <- roc(trump_shift$model$vote_trump,trump_shift$fitted.values,auc = T)
roc3 <- roc(trump_shift_i$model$vote_trump,trump_shift_i$fitted.values,auc = T)
roc4 <- roc(trump_shift_r$model$vote_trump,trump_shift_r$fitted.values,auc = T)

out <- data.frame(model=c(rep('Pooled',length(roc1$sensitivities)),
                          rep('Democrats',length(roc2$sensitivities)),
                          rep('Independents',length(roc3$sensitivities)), 
                          rep('Republicans',length(roc4$sensitivities))),
                  sp=c(roc1$specificities,roc2$specificities,roc3$specificities,roc4$specificities),
                  se=c(roc1$sensitivities,roc2$sensitivities,roc3$sensitivities,roc4$sensitivities)) 
out$model <- factor(out$model, levels=c('Pooled','Democrats','Independents','Republicans'))
g.out <- ggplot(out, aes(sp, y=se)) +
  geom_line() + 
  facet_wrap(~model) +
  scale_x_reverse() +
  geom_abline(slope = 1, intercept = 1,linetype=2) +
  labs(x='Specificity',y='Sensitivity') +
  theme_bw()
g.out
ggsave(g.out, width=5, height=5, file='figureI1.eps')
auc(roc1);auc(roc2);auc(roc3);auc(roc4)

png('figureI2.eps')
par(mfrow=c(4,1))
separationplot(trump_shift_all$fitted.values, trump_shift_all$model$vote_trump,heading = 'Pooled',newplot=F)
separationplot(trump_shift$fitted.values, trump_shift$model$vote_trump,heading = 'Democrats',newplot=F)
separationplot(trump_shift_i$fitted.values, trump_shift_i$model$vote_trump, heading = 'Independents', newplot=F)
separationplot(trump_shift_r$fitted.values, trump_shift_r$model$vote_trump, heading = 'Republicans', newplot=F)
dev.off()

####
form_vote_shift_clinton <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + college

all <- df$white_anglo ==1 &df$vote_obama==0 & df$voted_2012 == 1
subD <- df$white_anglo ==1 & df$pid3factor=='Democrat' & df$vote_obama==0 & df$voted_2012 == 1
subI <- df$white_anglo ==1 & df$pid3factor=='Independent' & df$vote_obama==0 & df$voted_2012 == 1
subR <- df$white_anglo ==1 & df$pid3factor=='Republican' & df$vote_obama==0 & df$voted_2012 == 1

cshift_all <-  glm(form_vote_shift_clinton, data = df[all,], family="binomial")
cshift <-  glm(form_vote_shift_clinton, data = df[subD,], family="binomial")
cshift_i <-  glm(form_vote_shift_clinton,data = df[subI,], family="binomial") 
cshift_r <-  glm(form_vote_shift_clinton,data = df[subR,], family="binomial")

roc1 <- roc(cshift_all$model$vote_clinton,cshift_all$fitted.values,auc = T)
roc2 <- roc(cshift$model$vote_clinton,cshift$fitted.values,auc = T)
roc3 <- roc(cshift_i$model$vote_clinton,cshift_i$fitted.values,auc = T)
roc4 <- roc(cshift_r$model$vote_clinton,cshift_r$fitted.values,auc = T)
out <- data.frame(model=c(rep('Pooled',length(roc1$sensitivities)),
                          rep('Democrats',length(roc2$sensitivities)),
                          rep('Independents',length(roc3$sensitivities)), 
                          rep('Republicans',length(roc4$sensitivities))),
                  sp=c(roc1$specificities,roc2$specificities,roc3$specificities,roc4$specificities),
                  se=c(roc1$sensitivities,roc2$sensitivities,roc3$sensitivities,roc4$sensitivities)) 
out$model <- factor(out$model, levels=c('Pooled','Democrats','Independents','Republicans'))
g.out <- ggplot(out, aes(sp, y=se)) +
  geom_line() + 
  facet_wrap(~model) +
  scale_x_reverse() +
  geom_abline(slope = 1, intercept = 1,linetype=2) +
  labs(x='Specificity',y='Sensitivity') +
  theme_bw()
g.out
ggsave(g.out, width=5, height=5, file='figureI3.eps')
auc(roc1);auc(roc2);auc(roc3);auc(roc4)

png('figureI4.eps')
par(mfrow=c(4,1))
separationplot(cshift_all$fitted.values, cshift_all$model$vote_clinton,heading = 'Pooled',newplot=F)
separationplot(cshift$fitted.values, cshift$model$vote_clinton,heading = 'Democrats',newplot=F)
separationplot(cshift_i$fitted.values, cshift_i$model$vote_clinton, heading = 'Independents', newplot=F)
separationplot(cshift_r$fitted.values, cshift_r$model$vote_clinton, heading = 'Republicans', newplot=F)
dev.off()

# Appendix J Table 1: Replication with Panel ----------------------------------

dfvsg <- read_csv('voter_survey_dfvsg_2017.csv')
demos <- read_csv('merged_demos.csv')
econ <- read_csv('merged_econ_context.csv')
income <- read_csv('med_county_family_income.csv')
econ$fips <- as.character(econ$fips)
context <- left_join(demos, econ, by = 'fips') %>% left_join(income, by='fips')

# zip
zipwalk <- read_csv('zip_county_walkfile.csv')
zipwalk$fips <- zipwalk$Geo_FIPS
dfvsg$zipcode <- dfvsg$izip_2016
dfvsg <- left_join(dfvsg,zipwalk,by='zipcode')

# Merge Survey with County-level Data
context$fips
dfvsg$fips <- as.character(dfvsg$fips)
dfvsg$fips <- str_pad(dfvsg$fips,5,'left','0')
dfvsg <- left_join(dfvsg, context, by='fips')

# Voting 2012

# Did you vote in the 2012 Presidential election? (yes / no)
dfvsg$vote_2012 <- ifelse(dfvsg$post_turnout12_2012==5,1,0)

#note that these drop those who didn't vote
dfvsg$vote_obama_2012 <- ifelse(dfvsg$post_presvote12_2012==1,1,0)
dfvsg$vote_romney_2012 <- ifelse(dfvsg$post_presvote12_2012==2,1,0)
dfvsg$vote_other_2012 <- ifelse(dfvsg$post_presvote12_2012==3,1,0)

dfvsg$voted_trump <- ifelse(dfvsg$presvote16post_2016 == 2,1,0)
dfvsg$voted_clinton <- ifelse(dfvsg$presvote16post_2016 == 1,1,0)

# Economic Indicators

#retrospective personal econ
dfvsg$persfinretro_2016[dfvsg$persfinretro_2016>3] <- NA
dfvsg$personal_econ_worse <- (dfvsg$persfinretro_2016-1)/2
table(dfvsg$personal_econ_worse)

# Relative Deprivation #
dfvsg$faminc_2016[dfvsg$faminc_2016 >= 12] <- 12
dfvsg$faminc_2016[dfvsg$faminc_2016 == 97] <- NA
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income < 10000] <- 1
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 10000 & dfvsg$med_family_income < 20000] <- 2
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 20000 & dfvsg$med_family_income < 30000] <- 3
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 30000 & dfvsg$med_family_income < 40000] <- 4
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 40000 & dfvsg$med_family_income < 50000] <- 5
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 50000 & dfvsg$med_family_income < 60000] <- 6
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 60000 & dfvsg$med_family_income < 70000] <- 7   
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 70000 & dfvsg$med_family_income < 80000] <- 8    
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 80000  & dfvsg$med_family_income < 100000] <- 9     
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 100000 & dfvsg$med_family_income < 120000] <- 10     
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >= 120000 & dfvsg$med_family_income < 150000] <- 11
dfvsg$med_inc_census_1014_bin[dfvsg$med_family_income >=  150000 ] <- 12
dfvsg$relative_deprivate <- ifelse(dfvsg$faminc_2016 < dfvsg$med_inc_census_1014_bin, 1, 0) # 1=below county average income
table(pb$relative_deprivate)                                

# Racial Resentment

dfvsg$rr1 <- dfvsg$race_deservemore_baseline
dfvsg$rr2 <- abs(dfvsg$race_overcome_baseline - 6) #flip
dfvsg$rr3 <- abs(dfvsg$race_tryharder_baseline - 6) #flip
dfvsg$rr4 <- dfvsg$race_slave_baseline
cor(cbind(dfvsg$rr1, dfvsg$rr2, dfvsg$rr3, dfvsg$rr4),use='complete.obs')
dfvsg$rr_scale <- ((dfvsg$rr1 + dfvsg$rr2 + dfvsg$rr3 + dfvsg$rr4)-4)/16
range(dfvsg$rr_scale,na.rm=T)

# Immigration Threat

dfvsg$immigrants_drain_base <- dfvsg$immi_contribution_baseline
dfvsg$immigrants_drain_base[dfvsg$immigrants_drain_base == 8] <- 2

dfvsg$immigrants_naturalize_base <- dfvsg$immi_naturalize_baseline
dfvsg$immigrants_naturalize_base[dfvsg$immigrants_naturalize_base == 3] <- 2
dfvsg$immigrants_naturalize_base[dfvsg$immigrants_naturalize_base == 2] <- 3

dfvsg$immi_makedifficult_base <- dfvsg$immi_makedifficult_baseline
dfvsg$immi_makedifficult_base[dfvsg$immi_makedifficult_baseline ==8] <- 3

cor(cbind(dfvsg$immigrants_drain_base, dfvsg$immigrants_naturalize_base, dfvsg$immi_makedifficult_base),use='complete.obs')
dfvsg$anti_scale <- (dfvsg$immigrants_drain_base + dfvsg$immigrants_naturalize_base + dfvsg$immi_makedifficult_base-3)/8

#gender
dfvsg$female <- dfvsg$gender_baseline - 1
table(dfvsg$female)

#age
dfvsg$age <- 2011-dfvsg$birthyr_baseline

#married 
dfvsg$married <- ifelse(dfvsg$marstat_2016==1,1,0)

# state
dfvsg$state <- dfvsg$inputstate_2016

# family income
dfvsg$income_r <- dfvsg$faminc_2016

#education
dfvsg$college <- ifelse(dfvsg$educ_2016 >= 5,1,0)

# current job status
dfvsg$unemployed <- ifelse(dfvsg$employ_2016==4,1,0)

# south
dfvsg$south <- 0
dfvsg$south[dfvsg$state == 1 | # Alabama
           dfvsg$state == 5 | # Arkansas
           dfvsg$state == 12 | # Florida
           dfvsg$state == 13 | # Georgia
           dfvsg$state == 22 | # Louisiana
           dfvsg$state == 28 | # Mississippi
           dfvsg$state == 37 | # North Carolina
           dfvsg$state == 45 | # South Carolina
           dfvsg$state == 47 | # Tennessee    
           dfvsg$state == 48 | # Texas
           dfvsg$state == 51 ] <- 1 # Virginia
table(dfvsg$south)

#partyid
dfvsg$pid7_republican <- dfvsg$pid7_2016
dfvsg$pid7_republican[dfvsg$pid7_republican == 8] <- NA

dfvsg$party_3 <- NA
dfvsg$party_3[dfvsg$pid7_republican < 4] <- 'Democrat'  
dfvsg$party_3[dfvsg$pid7_republican == 4] <- 'Independent'  
dfvsg$party_3[dfvsg$pid7_republican > 4] <- 'Republican'  

# race 
dfvsg$white <- ifelse(dfvsg$race_baseline == 1,1,0)

#wwc
dfvsg$wwc <- ifelse(dfvsg$white==1 & dfvsg$college==0,1,0)

#union membership
dfvsg$union <- abs(dfvsg$labunmemb_2016-4)

dfvsg$ideo_lib_cons <- dfvsg$ideo5_2016
dfvsg$ideo_lib_cons[dfvsg$ideo_lib_cons == 6] <- 3

# subgroups

subAll <- dfvsg$white==1 & dfvsg$vote_romney_2012 == 0 & dfvsg$vote_2012 ==1
subWWC <- dfvsg$wwc==1 & dfvsg$vote_romney_2012 == 0 & dfvsg$vote_2012 == 1
subNWWC <- dfvsg$white==1 & dfvsg$wwc==0 & dfvsg$vote_romney_2012 == 0 & dfvsg$vote_2012 ==1

form <- voted_trump ~ 
  rr_scale + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + unemployed + fb_pchange_00_14 + 
  union + female +  ideo_lib_cons + south + college+
  pid7_republican

summary(glm.outA <- glm(form,dfvsg[subAll,],family=binomial(link='logit')))
summary(glm.outB <- glm(form,dfvsg[subWWC,],family=binomial(link='logit')))
summary(glm.outC <- glm(form,dfvsg[subNWWC,],family=binomial(link='logit')))

form <- voted_clinton ~  
  rr_scale + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + unemployed + fb_pchange_00_14 + 
  union + female +  ideo_lib_cons + south + college +
  pid7_republican

subAll <- dfvsg$white==1 & dfvsg$vote_obama_2012 == 0 & dfvsg$vote_2012 ==1
subWWC <- dfvsg$wwc==1 & dfvsg$vote_obama_2012 == 0 & dfvsg$vote_2012 == 1
subNWWC <- dfvsg$white==1 & dfvsg$wwc==0 & dfvsg$vote_obama_2012 == 0 & dfvsg$vote_2012 ==1

summary(glm.CA <- glm(form,dfvsg[subAll,],family=binomial(link='logit')))
summary(glm.CB <- glm(form,dfvsg[subWWC,],family=binomial(link='logit')))
summary(glm.CC <- glm(form,dfvsg[subNWWC,],family=binomial(link='logit')))


cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", 
              "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born Change",
              "Union (no, family, is)","Female","Ideology (lib-consv)", "South","College", "PID (Republican)", "Constant")

col_labs <- c("All Whites","WWC","Non-WC","All Whites","WWC","Non-WC")
stargazer(glm.outA,glm.outB,glm.outC,
          glm.CA,glm.CB,glm.CC,
          covariate.labels = cov_labs,
          column.labels=col_labs, title=tit,type = 'html',
          out="tableJ1.html",star.cutoffs = c(0.05, 0.01, 0.001))

# Appendix J Table 1: Who Are Obama > Trump Switchers? ----------------------------

df$ttest1 <- NA
df$ttest1[df$vote_romney==1 & df$vote_trump==1 & df$white_anglo==1 & df$voted_2012==1] <- 0
df$ttest1[df$vote_romney==0 & df$vote_trump==1 & df$white_anglo==1 & df$voted_2012==1] <- 1
df$ttest1[df$vote_obama==0 & df$vote_clinton==1 & df$white_anglo==1 & df$voted_2012==1] <- 1
df$ttest1[df$vote_obama==1 & df$vote_clinton==1 & df$white_anglo==1 & df$voted_2012==1] <- 1
svyout <- svydesign(~1,data = df, weights = df$commonweight)
svyttest(race_attitudes ~ ttest1,svyout)
svyttest(anti_scale ~ ttest1,svyout)

svymean(race_attitudes~white_anglo, svyout,na.rm=T)

# first more less racially restful than romney > trump
weighted.mean(df$race_attitudes[df$vote_trump==1 & df$white_anglo==1],na.rm=T,w = df$commonweight[df$vote_trump==1 & df$white_anglo==1])
weighted.mean(df$race_attitudes[df$vote_clinton==1 & df$white_anglo==1],na.rm=T,w = df$commonweight[df$vote_clinton==1 & df$white_anglo==1])
weighted.mean(df$race_attitudes[df$vote_romney==0 & df$vote_trump == 1 & df$white_anglo==1],na.rm=T,w = df$commonweight[df$vote_romney==0 & df$vote_trump == 1 & df$white_anglo==1])
weighted.mean(df$race_attitudes[df$vote_obama==0 & df$vote_clinton == 1 & df$white_anglo==1],na.rm=T,w = df$commonweight[df$vote_obama==0 & df$vote_clinton == 1 & df$white_anglo==1])
tout <- t.test(df$race_attitudes[df$vote_romney==1 & df$vote_trump==1 & df$white_anglo==1],df$race_attitudes[df$vote_obama==1 & df$vote_trump==1& df$white_anglo==1],)
(tout$estimate[1]-tout$estimate[2])/sd(df$anti_scale[df$white_anglo==1], na.rm=T)

#immigration attitudes
mean(df$anti_scale[df$vote_trump==1 & df$white_anglo==1],na.rm=T)
mean(df$anti_scale[df$vote_clinton==1 & df$white_anglo==1],na.rm=T)
mean(df$anti_scale[df$vote_romney==0 & df$vote_trump == 1 & df$white_anglo==1],na.rm=T)
mean(df$anti_scale[df$vote_obama==0 & df$vote_clinton == 1 & df$white_anglo==1],na.rm=T)
tout <- t.test(df$anti_scale[df$vote_romney==1 & df$vote_trump==1 & df$white_anglo==1],df$anti_scale[df$vote_obama==1 & df$vote_trump==1& df$white_anglo==1])
(tout$estimate[1]-tout$estimate[2])/sd(df$anti_scale[df$white_anglo==1], na.rm=T)


out <- data.frame(x=c('Obama-Clinton','Romney-Trump','Switch Trump','Switch Clinton'),
                  y=c(weighted.mean(df$race_attitudes[df$vote_obama == 1 & df$vote_clinton==1 & df$white_anglo == 1],na.rm=T, w=df$commonweight[df$vote_obama == 1 & df$vote_clinton==1 & df$white_anglo == 1]),
                      weighted.mean(df$race_attitudes[df$vote_romney == 1 & df$vote_trump==1 & df$white_anglo == 1],na.rm=T, w=df$commonweight[df$vote_romney == 1 & df$vote_trump==1 & df$white_anglo == 1]),
                      weighted.mean(df$race_attitudes[df$vote_romney == 0 & df$vote_trump==1 & df$white_anglo == 1],na.rm=T, w=df$commonweight[df$vote_romney == 0 & df$vote_trump==1 & df$white_anglo == 1]),
                      weighted.mean(df$race_attitudes[df$vote_obama == 0 & df$vote_clinton==1 & df$white_anglo == 1],na.rm=T, w=df$commonweight[df$vote_obama == 0 & df$vote_clinton==1 & df$white_anglo == 1])),
                  Attitude='Race')
out2 <- data.frame(x=c('Obama-Clinton','Romney-Trump','Switch Trump','Switch Clinton'),
                   y=c(weighted.mean(df$anti_scale[df$vote_obama == 1 & df$vote_clinton==1 & df$white_anglo == 1],na.rm=T, w=df$commonweight[df$vote_obama == 1 & df$vote_clinton==1 & df$white_anglo == 1]),
                       weighted.mean(df$anti_scale[df$vote_romney == 1 & df$vote_trump==1 & df$white_anglo == 1],na.rm=T, w=df$commonweight[df$vote_romney == 1 & df$vote_trump==1 & df$white_anglo == 1]),
                       weighted.mean(df$anti_scale[df$vote_romney == 0 & df$vote_trump==1 & df$white_anglo == 1],na.rm=T, w=df$commonweight[df$vote_romney == 0 & df$vote_trump==1  & df$white_anglo == 1]),
                       weighted.mean(df$anti_scale[df$vote_obama == 0 & df$vote_clinton==1 & df$white_anglo == 1],na.rm=T, w=df$commonweight[df$vote_obama == 0 & df$vote_clinton==1 & df$white_anglo == 1])),
                   Attitude='Immigration')
out <- bind_rows(out, out2)
out$x <- factor(out$x, levels=c('Switch Clinton','Obama-Clinton','Switch Trump','Romney-Trump'))
out$color <- 'Trump'
out$color[grep('Clinton',out$x)] <- 'Clinton'
out$color<- factor(out$color, levels=c('Trump','Clinton'))
g.out <- ggplot(out, aes(x, y, fill=color)) +
  geom_point(size=10,shape=21,alpha=.5) +
  theme_bw() + 
  coord_flip() +
  labs(y='Mean Attitude (liberal-conservative)', x='') +
  facet_wrap(~Attitude,scales='free_x') +
  scale_fill_brewer(palette = 'Set1',name='2016 Vote') +
  geom_text(aes(x=x, y=y, label=round(y,2)*100), position=position_dodge(width=.5)) +
  scale_y_continuous(limits=c(0,0.8))
g.out
ggsave(g.out, width=6.5, height=2.5, file='figureK1.eps')

### Table L1 Mobilized by Trump/Clinton -------

form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 & df$voted_2012 == 0
trump_shift_all <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 &  df$white_anglo == 1 & df$voted_2012 == 0
trump_shift_wwc <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 & df$voted_2012 == 0
trump_shift_otherwhite <-  glm(form, data = df[subAll,], family="binomial")

form_vote_shift_clinton <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 & df$voted_2012 == 0
cshift <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 & df$white_anglo ==1 &  df$voted_2012 == 0
cshift_wwc <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 & df$voted_2012 == 0
cshift_otherwhite <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","Partisanship (R)","College", "Constant")

col_labs <- c("Trump All", "Trump WWC", "Trump Non-WWC",
              "Clinton All", "Clinton WWC", "Clinton Non-WWC")
tit <- "Full Model Pooled Across Partisan Categories"
stargazer(trump_shift_all, trump_shift_wwc, trump_shift_otherwhite,
          cshift, cshift_wwc, cshift_otherwhite,
          column.labels=col_labs, covariate.labels = cov_labs,
          label="",
          type = 'html',
          dep.var.labels = '',
          out='tableL1.html',star.cutoffs = c(0.05, 0.01, 0.001))

# Table L2: demobilized by Trump Clinton -----------

form <- didnt_vote_2016 ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 & df$voted_2012 == 1 
trump_shift_all <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 &  df$white_anglo == 1 & df$voted_2012 == 1
trump_shift_wwc <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 & df$voted_2012 == 1
trump_shift_otherwhite <-  glm(form, data = df[subAll,], family="binomial")

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","Partisanship (R)","College", "Constant")

col_labs <- c("Trump All", "Trump WWC", "Trump Non-WWC",
              "Clinton All", "Clinton WWC", "Clinton Non-WWC")
tit <- "Demobilization"
stargazer(trump_shift_all, trump_shift_wwc, trump_shift_otherwhite,
          column.labels=col_labs, covariate.labels = cov_labs,
          label="",
          type = 'html',
          dep.var.labels = '',
          out='tableL2.html',star.cutoffs = c(0.05, 0.01, 0.001))

# Table M1: Swing states

# swing states as according to FiveThirtyEight
# https://fivethirtyeight.com/features/the-odds-of-an-electoral-college-popular-vote-split-are-increasing/

df$swing_state <- ifelse(df$inputstate %in% c(8,12,19, 26, 27, 39, 32, 33, 37, 42, 51, 55),1,0)

form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 & df$voted_2012 == 0 & swing_state == 1
trump_shift_all <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 &  df$white_anglo == 1 & df$voted_2012 == 0 & swing_state == 1
trump_shift_wwc <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 & df$voted_2012 == 0 & swing_state == 1
trump_shift_otherwhite <-  glm(form, data = df[subAll,], family="binomial")

form_vote_shift_clinton <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 & df$voted_2012 == 0 & swing_state == 1
cshift <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 & df$white_anglo ==1 &  df$voted_2012 == 0 & swing_state == 1
cshift_wwc <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 & df$voted_2012 == 0 & swing_state == 1
cshift_otherwhite <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","Partisanship (R)","College", "Constant")

col_labs <- c("Trump All", "Trump WWC", "Trump Non-WWC",
              "Clinton All", "Clinton WWC", "Clinton Non-WWC")
tit <- "Full Model Pooled Across Partisan Categories"
stargazer(trump_shift_all, trump_shift_wwc, trump_shift_otherwhite,
          cshift, cshift_wwc, cshift_otherwhite,
          column.labels=col_labs, covariate.labels = cov_labs,
          label="",
          type = 'html',
          dep.var.labels = '',
          out='tableM1.html',star.cutoffs = c(0.05, 0.01, 0.001))

# Table M2: 

form <- vote_trump ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + 
  manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 & df$voted_2012 == 0 & swing_state == 0
trump_shift_all <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 &  df$white_anglo == 1 & df$voted_2012 == 0 & swing_state == 0
trump_shift_wwc <-  glm(form, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 & df$voted_2012 == 0 & swing_state == 0
trump_shift_otherwhite <-  glm(form, data = df[subAll,], family="binomial")

form_vote_shift_clinton <- vote_clinton ~ 
  race_attitudes + anti_scale + lat_pchange_00_14 +
  personal_econ_worse + relative_deprivate + manu_pchange_00_14 + unem_pchange_00_14 +
  income_r + personal_unemployed + fb_pchange_00_14 + 
  union_comb + female +  ideo_lib_cons + south + pid3_r + college 

subAll <-  df$white_anglo ==1 & df$voted_2012 == 0 & swing_state == 0
cshift <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")
subAll <-  df$wwc ==1 & df$white_anglo ==1 &  df$voted_2012 == 0 & swing_state == 0
cshift_wwc <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")
subAll <-  df$wwc == 0 & df$white_anglo == 1 & df$voted_2012 == 0 & swing_state == 0
cshift_otherwhite <-  glm(form_vote_shift_clinton, data = df[subAll,], family="binomial")

cov_labs <- c("Racial Attitudes", "Immigration Attitudes", "Pct. Latino Growth (00-14)",
              "Personal Econ Situation Worse", "Relative Deprivation", "Pct. Manufacturing Loss (00-14)","Pct. Unemployment Diff (00-14)",
              "Family Income (low-high)", "Unemployed","Pct. Foreign Born",
              "Union (no, was, is)","Female","Ideology (lib-consv)", "South","Partisanship (R)","College", "Constant")

col_labs <- c("Trump All", "Trump WWC", "Trump Non-WWC",
              "Clinton All", "Clinton WWC", "Clinton Non-WWC")
tit <- "Full Model Pooled Across Partisan Categories"
stargazer(trump_shift_all, trump_shift_wwc, trump_shift_otherwhite,
          cshift, cshift_wwc, cshift_otherwhite,
          column.labels=col_labs, covariate.labels = cov_labs,
          label="",
          type = 'html',
          dep.var.labels = '',
          out='tableM2.html',star.cutoffs = c(0.05, 0.01, 0.001))

